package com.tianyadu.security.controller;

import com.tianyadu.security.domain.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @FileName: FileController
 * @Description: 文件控制类
 * @author: xueyj
 * @create: 2018-12-05 07:55
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    private String folder = "D:/springCloud/security/security-demo/src/main/java/com/tianyadu/security/controller";

    /**
      * @Description: 文件上传
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/5 8:17
      */
    @PostMapping
    public FileInfo upload(MultipartFile file) throws Exception {
        log.info("上传文件信息，文件名：【{}】，原始文件名：【{}】，文件size：【{}】",
                file.getName(), file.getOriginalFilename(), file.getSize());
        //  构建本地文件信息
        File localFile = new File(folder, System.currentTimeMillis() + ".txt");
        //  拷贝文件信息至本地文件
        file.transferTo(localFile);
        //  返回上传后的文件路径信息
        return new FileInfo(localFile.getAbsolutePath());
    }

    /**
      * @Description: 文件下载
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/5 14:02
      */
    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
             OutputStream outputStream = response.getOutputStream();) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");

            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }

}